package org.ffrl.design.singleton;

import java.util.concurrent.atomic.AtomicReference;

/**
 * CAS 模式单例，乐观锁
 * 
 * @author  zhangpeijun[zhangpeijun1024@qq.com]
 * @version  [v1.0.1, 2017年9月14日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class Singleton {
    
    private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>(); 

    private Singleton() {}

    public static Singleton getInstance() {
        for (;;) {
            Singleton singleton = INSTANCE.get();
            if (null != singleton) {
                return singleton;
            }

            singleton = new Singleton();
            if (INSTANCE.compareAndSet(null, singleton)) {
                return singleton;
            }
        }
    }
}